<?php
namespace app\wxapplet\controller;

use app\admin\model\WechatUserModel;
use app\common\helper\Obj2Array;
use think\Request;
use app\common\wx\Temp;
use app\yxwadmin\controller\Admin;

class Formid extends Admin
{
    public function index(){
        $appletlist = model("WechatAppletModel")->where("product_code","photo_albums_bless")->select();
        $userM = new WechatUserModel();
        $userlist =$userM->where(['is_system' => $userM::IS_SYSTEM_YES])->field(['applet_name' => 'name', 'original_id', 'openid', 'nick_name'])->select();
        if (!empty($userlist)) {
            $userlist = Obj2Array::resObject2Array($userlist);
        }

        //var_dump($userlist);die;
        //var_dump($userlist);die;
        //->join("WxApplet b","a.original_id=b.original_id")->where("product_code","photo_albums_bless")->select();

        $this->assign('userlist',$userlist);
        $this->assign('appletlist',$appletlist);
        return $this->view->fetch('formid/index'); 
    }

    public function getlist(){
        $limit = input('post.limit','0','trim');
        $offset = input('post.offset','0','trim');
        $sortName = input('post.sortName','id','trim');
        $sortOrder = input('post.sortOrder','asc','trim');
        $keyword = input('post.keyword','','trim');
        $originalid = input('post.original_id','','trim');
        $openid = input('post.openid','','trim');
        $sendstate = input('post.sendstate/d', -1);

        $where['product_code'] = "photo_albums_bless";
        if(!empty($keyword)){
            $where['openid']=array('like','%'.$keyword.'%');
        }
        if(!empty($openid)){
            $where['openid'] = $openid;
        }
        if(!empty($originalid)){
            $where['a.original_id'] = $originalid;
        }
        if($sendstate!=-1){
            $where['sendstate'] = $sendstate;
        }

        $count = model('WechatUserFormidModel')->alias('a')
        ->join("WxApplet b","a.original_id=b.original_id")->where($where)->count(); //查询满足要求的总记录数
        $list = model('WechatUserFormidModel')->alias('a')->field("a.*,b.name")
        ->join("WxApplet b","a.original_id=b.original_id")
        ->where($where)->order([$sortName=>$sortOrder])->limit($offset,$limit)->select();

        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    public function template(){
        $original_id = input('original_id');
        $appletlist = model("WechatAppletModel")->where("original_id",$original_id)->where("product_code","photo_albums_bless")->select();
        $template = new Temp();
        $data = array();
        $templatedata = array();
        foreach($appletlist as $applet){
            $data[$applet["original_id"]] = $applet["name"];
            //获取模版信息
            $templatelist = $template->mylist($applet["original_id"],0,20);
            foreach($templatelist['list'] as $tmp){
                $templatedata[$tmp["template_id"]] = $tmp["title"];
            }
        }
        $this->assign('appletlist',$appletlist);
        $this->assign('data', json_encode($data));
        $this->assign('templatelist', json_encode($templatedata));
        $this->assign('id', input('id'));
        $this->assign('original_id', input('original_id'));
        return $this->view->fetch('formid/template');
    }

    public function getTemplateList(){
        $limit = input('post.limit','0','trim');
        $offset = input('post.offset','0','trim');
        $sortName = input('post.sortName','id','trim');
        $sortOrder = input('post.sortOrder','asc','trim');
        $keyword = input('post.keyword','','trim');
        $originalid = input('get.original_id','','trim');

        $where = array();
        if(!empty($keyword)){
            $where['temp_name']=array('like','%'.$keyword.'%');
        }
        $where['original_id'] = $originalid;

        $count = model('TemplateModel')->where($where)->count(); //查询满足要求的总记录数
        $list = model('TemplateModel')->where($where)->field('id,original_id,template_id,pageurl,temp_name,addtime')->order($sortName.' '.$sortOrder)->limit($offset,$limit)->select();
        
        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    /**
     * 发送单个模版消息
     */
    public function sendTemplateMsg(){
        if (Request::instance()->isPost()){
            $id = input("id");
            $template_id = input("template_id");
            $template = model("TemplateModel")->find($template_id);
            $formid_data = model("WechatUserFormidModel")->find($id);
            $msgData = array(
                "touser"=>$formid_data['openid'],
                "template_id"=>$template['template_id'],
                "page"=>$template['pageurl'],
                "form_id"=>$formid_data['formid'],
                "emphasis_keyword"=>$template['emphasis'],
                "data"=>json_decode($template['template_data'],true)
            );
            $template = new Temp();
            $rest = $template->sendTemplate($formid_data['original_id'],$msgData);
            if($rest['errcode']==0){
                $data['sendstate'] = 2;
                if(model("WechatUserFormidModel")->allowField(true)->save($data,["id"=>$formid_data['id']])){
                    $retdata['code'] = 0;
                    $retdata['msg']="发送成功！";
                    return json($retdata);
                }else{
                    $retdata['code'] = 1;
                    $retdata['msg']="模版发送成功，更改数据库状态失败！";
                    return json($retdata);
                }
            }else{
                $retdata['code'] = 1;
                $retdata['msg']="发送失败！".json_encode($rest);
                return json($retdata);
            }
        }
    }

    /**
     * 统计formid
     */
    public function statist(){
        $appletlist = model("WechatAppletModel")->where("product_code","photo_albums_bless")->select();
       
        $this->assign('appletlist',$appletlist);       
        return $this->view->fetch('formid/statist'); 
    }

    public function getstatistlist(){
        $limit = input('post.limit','0','trim');
        $offset = input('post.offset','0','trim');
        $sortName = input('post.sortName','a.id','trim');
        $sortOrder = input('post.sortOrder','asc','trim');
        $keyword = input('post.keyword','','trim');
        $originalid = input('post.original_id','','trim');
        $sendstate = input('post.sendstate/d');

        $where['product_code'] = "photo_albums_bless";
        if(!empty($keyword)){
            $where['openid']=array('like','%'.$keyword.'%');
        }
        if(!empty($originalid)){
            $where['a.original_id'] = $originalid;
        }
        if($sendstate!=-1){
            $where['sendstate'] = $sendstate;
        }

        $count = model('WechatUserFormidModel')->alias('a')->join("WxApplet b","a.original_id=b.original_id")
        ->where($where)->group('wx_user_id')->count(); //查询满足要求的总记录数
        $list = model('WechatUserFormidModel')->alias('a')->field("openid,b.name,count(1) num")
        ->join("WxApplet b","a.original_id=b.original_id")->where($where)->group('wx_user_id')
        ->order([$sortName=>$sortOrder])->limit($offset,$limit)->select();
        
        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    public function user(){
        $appletlist = model("WechatAppletModel")->where("product_code","photo_albums_bless")->select();
        $data = array();        
        foreach($appletlist as $applet){
            $data[$applet["original_id"]] = $applet["name"];            
        }
        $this->assign('appletlist',$appletlist);
        $this->assign('data', json_encode($data));
        return $this->view->fetch('formid/user'); 
    }

    public function getuserlist(){
        $limit = input('post.limit','0','trim');
        $offset = input('post.offset','0','trim');
        $sortName = input('post.sortName','id','trim');
        $sortOrder = input('post.sortOrder','asc','trim');
        $keyword = input('post.keyword','','trim');
        $originalid = input('post.original_id','','trim');        

        $where = array();
        if(!empty($keyword)){
            $where['openid']=array('like','%'.$keyword.'%');
        }
        if(!empty($originalid)){
            $where['original_id'] = $originalid;
        }

        $count = model('SysWechatUserModel')->alias('a')->field("a.*")->join("WxApplet b","a.original_id=b.original_id")->where("product_code","photo_albums_bless")->where($where)->count(); //查询满足要求的总记录数
        $list = model('SysWechatUserModel')->alias('a')->field("a.*")->join("WxApplet b","a.original_id=b.original_id")->where("product_code","photo_albums_bless")->where($where)->order($sortName.' '.$sortOrder)->limit($offset,$limit)->select();
        
        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    public function clearsucc(){
        if ( Request::instance()->isPost() ) {
            $res = model("WechatUserFormidModel")->where("sendstate",2)->delete();
            if($res){
                $ret["code"]=0;
                $ret['msg']="删除成功";
            }
            else{
                $ret["code"]=1;
                $ret['msg']="删除失败";
            }
            return json($ret);
        }
    }

    public function clearfail(){
        if ( Request::instance()->isPost() ) {
            $res = model("WechatUserFormidModel")->where("sendstate",1)->delete();
            if($res){
                $ret["code"]=0;
                $ret['msg']="删除成功";
            }
            else{
                $ret["code"]=1;
                $ret['msg']="删除失败";
            }
            return json($ret);
        }
    }

    public function edituser(){
        //判断提交方式 做不同的处理
        if (Request::instance()->isPost()){
            $data=input('post.');          
            $data['uptime'] = time();
            $res=model('SysWechatUserModel')->allowField(true)->save($data,['id' => $data['id']]);
            if($res){
                $ret["code"]=0;
                $ret['msg']="修改成功";
            }
            else{
                $ret["code"]=1;
                $ret['msg']="修改失败";
            }
            return $ret;
        }else{
            $id = input('get.id');
            $data = model('SysWechatUserModel')->find($id);
            $appletlist = model("WechatAppletModel")->select();
            foreach($appletlist as $key => $applet){
                if($applet['original_id'] == $data['original_id']){
                    $data['original_name'] = $applet['name'];
                }
            }

            $this->assign('data',$data);
            return $this->view->fetch('formid/edituser');
        }
    }

    /**
     * 删除系统用户
     */
    public function delsysuser(){
        //判断提交方式 做不同的处理
        if (Request::instance()->isPost()){
            $id=input('id');
            $res=model('SysWechatUserModel')->where("id",$id)->delete();
            if($res){
                $ret["code"]=0;
                $ret['msg']="删除成功";
            }
            else{
                $ret["code"]=1;
                $ret['msg']="删除失败";
            }
            return $ret;
        }else{
            $ret["code"]=1;
            $ret['msg']="删除失败";
            return $ret;
        }
    }
}